package com.qf.agro.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.agro.common.CustomerException;
import com.qf.agro.common.SysUserHolder;
import com.qf.agro.mapper.SysModuleMapper;
import com.qf.agro.mapper.SysRoleMapper;
import com.qf.agro.pojo.SysRole;
import com.qf.agro.service.SysModuleService;
import com.qf.agro.service.SysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * ProjectName: smart-agriculture-parent
 * ClassName: SysRoleServiceImpl
 * Author: chenyaosen
 * Date: 2023/7/3 11:54
 * Description:
 */
@Service
@Transactional
public class SysRoleServiceImpl implements SysRoleService {

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysModuleService moduleService;

    @Override
    public Page<SysRole> findPage(Integer pageNum, Integer pageSize, String name) {
        Page<SysRole> page = new Page<>(pageNum,pageSize);
        LambdaQueryWrapper<SysRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(name != null, SysRole::getName,name);
        page = roleMapper.selectPage(page, queryWrapper);
        return page;
    }

    @Override
    public void save(SysRole sysRole) {
        sysRole.setOrderNo(1l);
        roleMapper.insert(sysRole);
    }

    @Override
    public void update(SysRole sysRole) {
        roleMapper.updateById(sysRole);
    }

    @Override
    public void delete(Long id) {
        List<Long> sysModules = moduleService.findRoleModule(id);
        if (sysModules == null || sysModules.size() == 0) {
            roleMapper.deleteById(id);
        } else {
            throw new CustomerException("该角色有权限关联，请先删除权限");
        }
    }

    @Override
    public List<SysRole> findList() {
        LambdaQueryWrapper<SysRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysRole::getCompanyId, SysUserHolder.get().getCompanyId());
        return roleMapper.selectList(queryWrapper);
    }

    @Override
    public List<Long> findUserRole(Long userId) {
        return roleMapper.selectUserRole(userId);
    }

    @Override
    public void updateUserRole(Long userId, List<Long> roleIds) {
        roleMapper.deleteUserRole(userId);
        if (roleIds !=null&&roleIds.size()>0){
            roleMapper.insertUserRole(userId,roleIds);
        }
    }
    //    roleMapper.deleteUserRole(userId);
    //    roleMapper.insertUserRole(userId, roleIds);
    //
}
